package cn.itcalvin.sncoal.cth.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcalvin.sncoal.cth.component.ConfigCacheUtils;
import cn.itcalvin.sncoal.cth.domain.*;
import cn.itcalvin.sncoal.cth.em.EmPfState;
import cn.itcalvin.sncoal.cth.mapper.main.*;
import cn.itcalvin.sncoal.cth.pojo.common.ReqLong;
import cn.itcalvin.sncoal.cth.pojo.common.RespTotalRow;
import cn.itcalvin.sncoal.cth.pojo.common.RespUserInfo;
import cn.itcalvin.sncoal.cth.pojo.req.pf.*;
import cn.itcalvin.sncoal.cth.pojo.response.pf.*;
import cn.itcalvin.sncoal.cth.service.InfoPfService;
import cn.itcalvin.sncoal.cth.utils.JwtUtil;
import cn.itcalvin.sncoal.cth.utils.SnowFlakeUtils;
import cn.itcalvin.vo.Message;
import cn.itcalvin.vo.MessageExt;
import cn.itcalvin.vo.MessageUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class InfoPfServiceImpl implements InfoPfService{

    @Resource
    private InfoPfMapper infoPfMapper;
    @Resource
    private InfoPfSystemMapper infoPfSystemMapper;
    @Resource
    private InfoPfSystemZbMapper infoPfSystemZbMapper;

    @Resource
    private RelUserSystemMapper relUserSystemMapper;

    @Resource
    private InfoPfSystemZbDetailsMapper infoPfSystemZbDetailsMapper;

    @Resource
    private ConfigSystemZbDetailsExtMapper configSystemZbDetailsExtMapper;

    @Resource
    private ConfigSystemZbMapper configSystemZbMapper;
    @Resource
    private ConfigSystemZbDetailsMapper configSystemZbDetailsMapper;


    /**
     * 根据条件获取评分记录
     *
     * @param reqPfList
     * @return
     */
    @Override
    public Message<List<RespPfList>> list(ReqPfList reqPfList) {
        PageHelper.startPage(reqPfList.getPageIndex(),reqPfList.getPageSize());
        List<RespPfList> list= infoPfMapper.list(reqPfList);
        PageInfo<RespPfList> pageInfo=new PageInfo<>(list);
        return MessageUtil.success(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 新增任务
     * 将初始化15个系统以及300多项指标数据进行创建
     *
     * @param reqPfAdd
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message add(ReqPfAdd reqPfAdd) {
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("权限不足");
        }
        InfoPf infoPf=new InfoPf(){{
            setId(SnowFlakeUtils.getId());
            setCheckTime(reqPfAdd.getCheckTime());
            setCreateId(userInfo.getId());
            setCreateTime(DateUtil.date());
            setIsDelete(false);
            setMineId(userInfo.getBelongId());
            setTaskName(reqPfAdd.getTaskName());
            setTaskType(reqPfAdd.getTaskType());
            setState(1);
        }};
        int nCount = infoPfMapper.insert(infoPf);
        infoPfMapper.insertPfAndItemAndDetails(infoPf.getId(),userInfo);
        return nCount>0?MessageUtil.success():MessageUtil.error("新增失败！");
    }

    /**
     * 修改
     *
     * @param reqPfModify
     * @return
     */
    @Override
    public Message modify(ReqPfModify reqPfModify) {
        final val userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("权限不足");
        }
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqPfModify.getId());
        if(infoPf==null){
            return MessageUtil.error("修改失败！");
        }
        if(infoPf.getState()>EmPfState.已自评待核验.getCode()){
            return MessageUtil.error("已检查核验的评分不允许修改！");
        }
        infoPf.setCheckTime(reqPfModify.getCheckTime());
        infoPf.setTaskName(reqPfModify.getTaskName());
        infoPf.setTaskType(reqPfModify.getTaskType());
        infoPf.setModifyId(JwtUtil.getUserInfo().getId());
        infoPf.setModifyTime(DateUtil.date());
        final int nCount = infoPfMapper.updateByPrimaryKey(infoPf);
        return nCount>0?MessageUtil.success():MessageUtil.error("修改失败！");
    }

    /**
     * 删除
     *
     * @param reqLong
     * @return
     */
    @Override
    public Message delete(ReqLong reqLong) {
        final val userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("权限不足");
        }
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqLong.getId());
        if(infoPf==null){
            return MessageUtil.error("删除失败！");
        }
        if(infoPf.getState()>EmPfState.待自评.getCode()){
            return MessageUtil.error("该评分不允许删除！");
        }
        infoPf.setIsDelete(true);
        infoPf.setDeleteId(JwtUtil.getUserInfo().getId());
        infoPf.setDeleteTime(DateUtil.date());
        final int nCount = infoPfMapper.updateByPrimaryKey(infoPf);
        infoPfMapper.deletePfAndItemAndDetails(reqLong.getId());
        return nCount>0?MessageUtil.success():MessageUtil.error("删除失败！");
    }

    /**
     * 评分任务详情
     *
     * @param reqLong
     * @return
     */
    @Override
    public Message<RespPfDetails> details(ReqLong reqLong) {
        RespPfDetails respPfDetails= infoPfMapper.details(reqLong.getId());
        return MessageUtil.success(respPfDetails);
    }

    /**
     * 评分系统列表
     *
     * @param reqLong
     * @return
     */
    @Override
    public MessageExt<List<RespPfListSystem>, RespTotalRow> systemList(ReqLong reqLong) {
        final List<RespPfListSystem> respPfListSystems = infoPfMapper.systemList(reqLong.getId());
        //这里需要判断权限了
        final val userInfo = JwtUtil.getUserInfo();
        List<RespPfListSystem> resultList=new ArrayList<>();
        if(userInfo.getRoleType()==4&&userInfo.getIsManager()==false){
            final val relUserSystemList = relUserSystemMapper.selectByExample(Example.builder(RelUserSystem.class).where(Sqls.custom()
                    .andEqualTo("userId", userInfo.getId())).build());
            resultList=respPfListSystems.stream().filter(item->relUserSystemList.stream().anyMatch(relUserSystem -> relUserSystem.getSystemId().equals(item.getSystemId()))).collect(Collectors.toList());
        }else{
            resultList=respPfListSystems;
        }
        RespTotalRow result=null;
        if(respPfListSystems!=null&&respPfListSystems.size()>0){
            result = new RespTotalRow(){{
                setPfScoreWeight(respPfListSystems.stream().map(RespPfListSystem::getPfScoreWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
                if(respPfListSystems.get(0).getTaskType() == 2 &&
                        respPfListSystems.get(0).getHyScore()!=null
                ){
                    setHyScoreWeight(respPfListSystems.stream().map(RespPfListSystem::getHyScoreWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
                }
            }};
        }

        return MessageUtil.success(resultList,result);
    }

    /**
     * 某次评分的某个系统下的指标列表
     *
     * @param reqPfItemList
     * @return
     */
    @Override
    public Message<List<RespPfItemList>> pfItemList(ReqPfItemList reqPfItemList) {
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqPfItemList.getId());
        if(infoPf==null){
            return MessageUtil.error("获取失败！");
        }

        List<RespPfItemList> list=infoPfMapper.pfItemList(reqPfItemList, infoPf.getMineId());
        final List<Long> collect = list.stream().map(RespPfItemList::getId).collect(Collectors.toList());

        final List<InfoPfSystemZbDetails> infoPfItemDetails = infoPfSystemZbDetailsMapper.selectByExample(
                Example.builder(InfoPfSystemZbDetails.class).where(Sqls.custom()
                        .andEqualTo("isDelete",false)
                        .andEqualTo("pfId",reqPfItemList.getId())
                        .andIn("pfSystemZbId",collect)
                ).build());
        final List<Long> systemZbDetailsIdList = infoPfItemDetails.stream().map(InfoPfSystemZbDetails::getSystemZbDetailsId).collect(Collectors.toList());
        final val configSystemZbDetailsExtList = configSystemZbDetailsExtMapper.selectByExample(Example.builder(ConfigSystemZbDetailsExt.class)
                .where(Sqls.custom().andEqualTo("isDelete", false)
                        .andEqualTo("mineId", infoPf.getMineId())
                        .andIn("systemZbDetailsId", systemZbDetailsIdList)).build());
        list.forEach(x->{
            x.setRespPfItemDetailsListList(
                    infoPfItemDetails.stream().filter(z->z.getPfSystemZbId().equals(x.getId()))
                            .map(v-> new RespPfItemDetailsList(){{
                        setId(v.getId());
                        setPfZbDetails(v.getPfZbDetails());
                        setPfZbDetailsContent(v.getPfZbDetailsContent());
                        setPfZbDetailsType(v.getPfZbDetailsType());
                        setPfZbDetailsUnit(v.getPfZbDetailsUnit());
                        setHyZbDetailsContent(v.getHyZbDetailsContent());
                        setPfSystemZbId(v.getPfSystemZbId());
                        setSystemZbDetailsId(v.getSystemZbDetailsId());
                        setSystemZbId(v.getSystemZbId());
                        setPfSystemId(v.getPfSystemId());
                        setSystemId(v.getSystemId());
                        setMineId(v.getMineId());
                        setPfId(v.getPfId());
                        setZbDetailsRemark(v.getZbDetailsRemark());
                        final Optional<ConfigSystemZbDetailsExt> first = configSystemZbDetailsExtList.stream()
                                .filter(z -> z.getSystemZbDetailsId().equals(v.getSystemZbDetailsId())).findFirst();
                        setSystemZbDetailsCodeId(first.isPresent() ? first.get().getSystemZbDetailsCodeId() : null);
                    }}).sorted(Comparator.comparing(RespPfItemDetailsList::getSystemZbDetailsId))
                            .collect(Collectors.toList())
            );
        });
        return MessageUtil.success(list);
    }

    /**
     * 判断某个系统是否已经提交
     * type=1 自评  type=2 核验
     * @param reqPfItemList
     * @return
     */
    @Override
    public Message<RespPfItemState> pfItemListState(ReqPfItemList reqPfItemList,Integer type) {
        RespPfItemState respPfItemState=infoPfMapper.pfItemListState(reqPfItemList,type);
        return MessageUtil.success(respPfItemState);
    }

    /**
     * 保存指标填写---核验和自评共用一个接口
     * 1.先判断当前评分状态
     * 2.判断角色身份，如果是核验，则又判断状态
     * @param reqPfSystemZbDetailsAdd
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message savePfZbDetails(ReqPfSystemZbDetailsAdd reqPfSystemZbDetailsAdd) {
        final val infoPfSystem = infoPfSystemMapper.selectByPrimaryKey(reqPfSystemZbDetailsAdd.getPfSystemId());
        final val userInfo = JwtUtil.getUserInfo();
        /**
         * 判断状态
         */
        if(userInfo.getRoleType()==3){
            if(infoPfSystem.getHyState()==2){
                return MessageUtil.error("该评分不允许修改！");
            }
        }else{
            if(userInfo.getRoleType()==4){
                if(infoPfSystem.getZpState()==2){
                    return MessageUtil.error("该评分不允许修改！");
                }
            }
        }
        /**
         * 用户角色判断保存的数据
         */
        if(userInfo.getRoleType()==3){
            final val infoPfSystemZbDetails = infoPfSystemZbDetailsMapper.selectByPrimaryKey(reqPfSystemZbDetailsAdd.getPfSystemZbDetailsId());
            infoPfSystemZbDetailsMapper.updateByPrimaryKeySelective(new InfoPfSystemZbDetails(){{
                setHyZbDetailsContent(reqPfSystemZbDetailsAdd.getZbDetailsContent());
                setId(reqPfSystemZbDetailsAdd.getPfSystemZbDetailsId());
            }});
            infoPfSystemZbMapper.updateByPrimaryKeySelective(new InfoPfSystemZb(){{
                setHyScore(reqPfSystemZbDetailsAdd.getZbScore());
                setId(reqPfSystemZbDetailsAdd.getPfSystemZbId());
            }});
        }else{
            if(userInfo.getRoleType()==4){
                infoPfSystemZbDetailsMapper.updateByPrimaryKeySelective(new InfoPfSystemZbDetails(){{
                    setPfZbDetailsContent(reqPfSystemZbDetailsAdd.getZbDetailsContent());
                    setId(reqPfSystemZbDetailsAdd.getPfSystemZbDetailsId());
                }});
                infoPfSystemZbMapper.updateByPrimaryKeySelective(new InfoPfSystemZb(){{
                    setPfScore(reqPfSystemZbDetailsAdd.getZbScore());
                    setId(reqPfSystemZbDetailsAdd.getPfSystemZbId());
                }});
            }
        }
        return MessageUtil.success();
    }

    /**
     * 评分系统提交
     * 1.判断状态
     * 2.判断角色身份
     * @param reqCommitPfSystem
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message commitPfSystem(ReqCommitPfSystem reqCommitPfSystem) {
        final val userInfo = JwtUtil.getUserInfo();
        final val infoPfSystem = infoPfSystemMapper.selectByPrimaryKey(reqCommitPfSystem.getPfSystemId());
        if(infoPfSystem==null){
            return MessageUtil.error("该系统数据不存在！");
        }
        // 判断状态
        if(userInfo.getRoleType()==3&&infoPfSystem.getHyState()==2){
            return MessageUtil.error("该评分不允许提交！");
        }if(userInfo.getRoleType()==4&&infoPfSystem.getZpState()==2){
            return MessageUtil.error("该评分不允许提交！");
        }

        //判断角色,同时判断是否需要修改主任务的状态
        if(userInfo.getRoleType()==3){
            infoPfSystemMapper.updateByPrimaryKeySelective(new InfoPfSystem(){{
                setHyState(2);
                setId(reqCommitPfSystem.getPfSystemId());
                setModifyId(userInfo.getId());
                setModifyTime(DateUtil.date());
                setHyPerson(userInfo.getUserName());
                setHyTime(DateUtil.date());
            }});
        }else if(userInfo.getRoleType()==4){
            infoPfSystemMapper.updateByPrimaryKeySelective(new InfoPfSystem(){{
                setZpState(2);
                setId(reqCommitPfSystem.getPfSystemId());
                setModifyId(userInfo.getId());
                setModifyTime(DateUtil.date());
                setPfPerson(userInfo.getUserName());
                setPfTime(DateUtil.date());
                if(StrUtil.isNotBlank(reqCommitPfSystem.getZpRemark())){
                    setZpRemark(reqCommitPfSystem.getZpRemark());
                }
            }});
        }else{
            return MessageUtil.error("权限不足");
        }
        return MessageUtil.success();
    }

    /**
     * 复制评分任务
     *
     * @param reqPfCopy
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message copyPfTask(ReqPfCopy reqPfCopy) {
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("权限不足");
        }
        InfoPf infoPf=new InfoPf(){{
            setId(SnowFlakeUtils.getId());
            setCheckTime(reqPfCopy.getCheckTime());
            setCreateId(userInfo.getId());
            setCreateTime(DateUtil.date());
            setIsDelete(false);
            setMineId(userInfo.getBelongId());
            setTaskName(reqPfCopy.getTaskName());
            setTaskType(reqPfCopy.getTaskType());
            setState(1);
        }};
        infoPfMapper.insert(infoPf);
        final List<ConfigSystemZb> configSystemZbs = ConfigCacheUtils.getInstance().getAllZbByMineId(userInfo.getBelongId());

        final List<ConfigSystemZbDetails> configSystemZbDetails = ConfigCacheUtils.getInstance().getAllZbDetailsByMineId(userInfo.getBelongId());

        final List<ConfigSystem> configSystems = ConfigCacheUtils.getInstance().getAllSystemList();

        final List<InfoPfSystemZb> infoPfSystemZbs = infoPfSystemZbMapper.selectByExample(Example.builder(InfoPfSystemZb.class).where(Sqls.custom()
                .andEqualTo("pfId", reqPfCopy.getPfId())
                .andEqualTo("isDelete", false)).build());




        final List<InfoPfSystemZbDetails> infoPfSystemZbDetails = infoPfSystemZbDetailsMapper.selectByExample(Example.builder(InfoPfSystemZbDetails.class).where(Sqls.custom()
                        .andEqualTo("pfId", reqPfCopy.getPfId())
                        .andEqualTo("isDelete", false))
                .build());
        List<InfoPfSystem> newListSystem=new ArrayList<>();
        List<InfoPfSystemZb> newListSystemZb=new ArrayList<>();
        List<InfoPfSystemZbDetails> newListSystemZbDetails=new ArrayList<>();

        configSystems.forEach(x->{
            newListSystem.add(new InfoPfSystem(){{
                setId(SnowFlakeUtils.getId());
                setCreateId(userInfo.getId());
                setCreateTime(DateUtil.date());
                setIsDelete(false);
                setMineId(userInfo.getBelongId());
                setPfId(infoPf.getId());
                setZpState(1);
                setHyState(null);
                setPfPerson(null);
                setHyPerson(null);
                setSystemId(x.getId());
                setSystemName(x.getSystemName());
            }});
        });
        infoPfSystemMapper.insertListAllFiled(newListSystem);

        configSystemZbs.forEach(x->{
            newListSystemZb.add(new InfoPfSystemZb(){
                {
                    setId(SnowFlakeUtils.getId());
                    setCreateId(userInfo.getId());
                    setCreateTime(DateUtil.date());
                    setIsDelete(false);
                    setMineId(userInfo.getBelongId());
                    setPfId(infoPf.getId());
                    final ConfigSystem systemById = ConfigCacheUtils.getInstance().getSystemById(x.getSystemId());
                    if(systemById==null){
                        throw new RuntimeException("系统数据不存在");
                    }
                    setSystemName(systemById.getSystemName());
                    setWeight(systemById.getWeight());
                    final Optional<InfoPfSystemZb> first = infoPfSystemZbs.stream().filter(v -> v.getSystemZbId().equals(x.getId())).findFirst();
                    if(first.isPresent()){
                        setPfScore(first.get().getPfScore());
                    }else{
                        if(ConfigCacheUtils.zbIdList60.contains(x.getId())){
                            setPfScore(x.getZbTotalScore().multiply(BigDecimal.valueOf(0.6)));
                        }else if(ConfigCacheUtils.zbIdList100.contains(x.getId())){
                            setPfScore(x.getZbTotalScore());
                        }
                    }
                    setPfContent(null);
                    setSystemId(x.getSystemId());
                    setContent(x.getContent());
                    setContentDesc(x.getContentDesc());
                    setPfMethod(x.getPfMethod());
                    setSystemZbId(x.getId());
                    setZbContent(x.getZbContent());
                    setZbTotalScore(x.getZbTotalScore());
                    setPfSystemId(newListSystem.stream().filter(v->v.getSystemId().equals(x.getSystemId())).findFirst().get().getId());
                }
            });
        });
        infoPfSystemZbMapper.insertListAllFiled(newListSystemZb);

        configSystemZbDetails.forEach(x->{
            newListSystemZbDetails.add(new InfoPfSystemZbDetails(){
                {
                    setId(SnowFlakeUtils.getId());
                    setCreateId(userInfo.getId());
                    setCreateTime(DateUtil.date());
                    setIsDelete(false);
                    setMineId(userInfo.getBelongId());
                    setPfId(infoPf.getId());
                    final Optional<InfoPfSystemZb> first = newListSystemZb.stream().filter(v -> v.getSystemZbId().equals(x.getSystemZbId())).findFirst();
                    if(!first.isPresent()){
                        throw new RuntimeException("系统指标数据不存在");
                    }
                    setPfSystemZbId(first.get().getId());
                    setPfZbDetails(x.getZbDetails());
                    setPfZbDetailsType(x.getZbDetailsType());
                    setPfZbDetailsUnit(x.getZbDetailsUnit());
                    final Optional<InfoPfSystemZbDetails> first1 = infoPfSystemZbDetails.stream().filter(v -> v.getSystemZbDetailsId().equals(x.getId())).findFirst();
                    if(first1.isPresent()){
                        setPfZbDetailsContent(first1.get().getPfZbDetailsContent());
                    }
                    final Optional<InfoPfSystem> first2 = newListSystem.stream().filter(v -> v.getSystemId().equals(x.getSystemId())).findFirst();
                    if(!first2.isPresent()){
                        throw new RuntimeException("系统数据不存在");
                    }
                    setZbDetailsRemark(x.getZbDetailsRemark());
                    setPfSystemId(first2.get().getId());
                    setSystemId(x.getSystemId());
                    setSystemZbDetailsId(x.getId());
                    setSystemZbId(x.getSystemZbId());
                }
            });
        });
        infoPfSystemZbDetailsMapper.insertListAllFiled(newListSystemZbDetails);
        return MessageUtil.success();
    }

    /**
     * 上传整改计划文件,并修改任务状态
     * 只有当状态=2 或者 自评待核验状态=3
     * @param reqUploadZgjh
     * @return
     */
    @Override
    public Message uploadZgjh(ReqUploadZgjh reqUploadZgjh) {
        final val userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("只有管理员才能操作");
        }
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqUploadZgjh.getPfId());
        if(infoPf==null){
            return MessageUtil.error("评分不存在");
        }
        if(infoPf.getState()!=EmPfState.已自评待核验.getCode()
                &&
                infoPf.getState()!=EmPfState.已核验待出整改计划.getCode()){
            return MessageUtil.error("当前任务状态不允许提交");
        }
        infoPf.setZgjhUrl(reqUploadZgjh.getZgjhUrl());
        infoPf.setState(EmPfState.已提交整改计划.getCode());
        infoPfMapper.updateByPrimaryKey(infoPf);
        return MessageUtil.success();
    }

    /**
     * 导出某任务各系统得分情况
     *
     * @param pfId
     */
    @Override
    public void exportPfById(Long pfId, HttpServletResponse response) throws IOException {
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(pfId);
        if(infoPf==null){
            return;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName= URLEncoder.encode(infoPf.getTaskName(),"UTF-8").replaceAll("\\+","%20");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        //获取本次的上一次评分
        InfoPf lastInfoPf=infoPfMapper.getLastPF(infoPf.getMineId(),infoPf.getCheckTime());

        if(infoPf.getTaskType()==2){
            List<RespPfExport> list=infoPfMapper.exportPfByIdHy(pfId);
            if(lastInfoPf!=null){
                List<RespPfExport> listLast=infoPfMapper.exportPfByIdHy(lastInfoPf.getId());
                if(list!=null&& listLast!=null){
                    list.forEach(x->{
                        final val first = listLast.stream().filter(v -> v.getSystemName().equals(x.getSystemName())).findFirst();
                        if(first.isPresent()){
                            if(lastInfoPf.getTaskType()==1){
                                x.setHyScoreZzLast(first.get().getPfScoreZz());
                            }else if(lastInfoPf.getTaskType()==2){
                                x.setHyScoreZzLast(first.get().getHyScoreZz());
                            }
                        }
                    });
                }
            }
            EasyExcel.write(response.getOutputStream(),RespPfExport.class).sheet(infoPf.getTaskName()).doWrite(list);
        }else{
            List<RespPfExportZp> list=infoPfMapper.exportPfByIdZp(pfId);
            if(lastInfoPf!=null){
                List<RespPfExport> listLast=infoPfMapper.exportPfByIdHy(lastInfoPf.getId());
                if(list!=null&& listLast!=null){
                    list.forEach(x->{
                        final val first = listLast.stream().filter(v -> v.getSystemName().equals(x.getSystemName())).findFirst();
                        if(first.isPresent()){
                            if(lastInfoPf.getTaskType()==1){
                                x.setPfScoreZzLast(first.get().getPfScoreZz());
                            }else if(lastInfoPf.getTaskType()==2){
                                x.setPfScoreZzLast(first.get().getHyScoreZz());
                            }
                        }
                    });
                }
            }
            EasyExcel.write(response.getOutputStream(),RespPfExportZp.class).sheet(infoPf.getTaskName()).doWrite(list);
        }

    }

    /**
     * 批量提交-自评或者核验
     *
     * @param reqBatchCommit
     * @return
     */
    @Override
    public Message batchCommit(ReqBatchCommit reqBatchCommit) {
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqBatchCommit.getPfId());
        if(infoPf==null){
            return MessageUtil.error("评分任务不存在");
        }
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        if(userInfo.getRoleType().equals(4)){
            if(infoPf.getState()!=EmPfState.待自评.getCode()){
                return MessageUtil.error("当前任务状态不允许提交");
            }
            infoPfMapper.modifyBySystemIdZp(reqBatchCommit,userInfo,2);
        }else if(userInfo.getRoleType().equals(3)){
            if(infoPf.getState()!=EmPfState.已自评待核验.getCode()||infoPf.getTaskType()!=2){
                return MessageUtil.error("当前任务状态不允许提交");
            }
            infoPfMapper.modifyBySystemIdHy(reqBatchCommit,userInfo,2);
        }else{
            return MessageUtil.error("权限不足");
        }
        return MessageUtil.success();
    }

    /**
     * 批量驳回
     * @param reqBatchCommit
     * @return
     */
    @Override
    public Message batchBhCommit(ReqBatchCommit reqBatchCommit) {
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqBatchCommit.getPfId());
        if(infoPf==null){
            return MessageUtil.error("评分任务不存在");
        }
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("权限不足，驳回只能管理员操作！");
        }
        if(userInfo.getRoleType().equals(4)){
            if(infoPf.getState()!=EmPfState.待自评.getCode()){
                return MessageUtil.error("当前任务状态不允许提交");
            }
            infoPfMapper.modifyBySystemIdZp(reqBatchCommit,userInfo,1);
        }else if(userInfo.getRoleType().equals(3)){
            if(infoPf.getState()!=EmPfState.已自评待核验.getCode()||infoPf.getTaskType()!=2){
                return MessageUtil.error("当前任务状态不允许提交");
            }
            infoPfMapper.modifyBySystemIdHy(reqBatchCommit,userInfo,1);
        }else{
            return MessageUtil.error("权限不足");
        }
        return MessageUtil.success();
    }

    /**
     * 任务提交
     * @param reqBatchCommit
     * @return
     */
    @Override
    public Message batchTaskCommit(ReqBatchCommit reqBatchCommit) {
        final RespUserInfo userInfo = JwtUtil.getUserInfo();
        if(!userInfo.getIsManager()){
            return MessageUtil.error("权限不足，驳回只能管理员操作！");
        }
        final InfoPf infoPf = infoPfMapper.selectByPrimaryKey(reqBatchCommit.getPfId());
        if(infoPf==null){
            return MessageUtil.error("评分任务不存在");
        }
        if(userInfo.getRoleType()==3){
            if(infoPf.getState()!=EmPfState.已自评待核验.getCode()){
                return MessageUtil.error("当前任务状态不允许提交");
            }
            final int i = infoPfSystemMapper.selectCountByExample(Example.builder(InfoPfSystem.class)
                    .where(Sqls.custom()
                            .andEqualTo("pfId", reqBatchCommit.getPfId())
                            .andEqualTo("hyState", 1))
                    .build());
            if(i>0){
                return MessageUtil.error("存在未评分的系统，无法提交本次评分任务！");
            }
            //修改任务状态
            infoPfMapper.updateByPrimaryKeySelective(new InfoPf(){{
                setId(reqBatchCommit.getPfId());
                setState(EmPfState.已核验待出整改计划.getCode());
                setModifyId(userInfo.getId());
                setModifyTime(DateUtil.date());
            }});
            return MessageUtil.success();
        }else if(userInfo.getRoleType()==4){
            if(infoPf.getState()!=EmPfState.待自评.getCode()){
                return MessageUtil.error("当前任务状态不允许提交");
            }
            //如果所有系统都已完成提交，需要设置任务状态到下一个环节
            final int i = infoPfSystemMapper.selectCountByExample(Example.builder(InfoPfSystem.class)
                    .where(Sqls.custom()
                            .andEqualTo("pfId", reqBatchCommit.getPfId())
                            .andEqualTo("zpState", 1))
                    .build());
            if(i>0){
                return MessageUtil.error("存在未评分的系统，无法提交本次评分任务！");
            }
            //修改任务状态
            infoPfMapper.updateByPrimaryKeySelective(new InfoPf(){{
                setId(reqBatchCommit.getPfId());
                setState(EmPfState.已自评待核验.getCode());
                setModifyId(userInfo.getId());
                setModifyTime(DateUtil.date());
            }});
            //同时将值赋值给核验
            infoPfMapper.copyZpDataToHy(reqBatchCommit.getPfId());
            return MessageUtil.success();
        }else{
            return MessageUtil.error("权限不足");
        }
    }

}
